package com.examplemartin.jpademo.interceptor;

import com.examplemartin.jpademo.pojo.po.MenuPO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.util.SessionUtil;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 权限拦截器
 */
@Slf4j
@Component
public class AuthorInterceptor implements HandlerInterceptor {
@Resource
private UserService userService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    HttpSession session = request.getSession();
    String requestURI = request.getRequestURI();


//      response.sendRedirect("/sys/login.do");

      UserPO loninUser = SessionUtil.getLoninUser();

      List<MenuPO> authorities = loninUser.getRole().getAuthorities();
      Boolean flag = false;
      for (MenuPO authority : authorities) {
        String url =authority.getUrl();

        log.info("url="+url);
        log.info("author url="+requestURI);
        if (url.equals(requestURI)){
//          log.info("该请求无权限，重定向到无权限提示页面，url=" + requestURI);

          flag = true;
          break;
        }
      }
      if(flag){
        log.info("AuthorInterceptor-uri 放行: "+requestURI);
      }else {
        log.info("AuthorInterceptor-uri 阻止: "+requestURI);
        response.sendRedirect("/sys/login.do");
      }


    return flag;
  }
}
